<?php
/**
 * Created by PhpStorm.
 * User: sunqiang
 * Date: 2018/8/17
 * Time: 下午6:27
 */

namespace wap\controllers;


use Yii;
use common\helps\api;
use common\helps\tools;

class LoginController extends CommonController
{


    /**
     * 校验签名
     * @param string $sign 签名
     * @param string $toSign 待签名字符串
     * @return   bool
     */
    private function checkSign($sign, $toSign)
    {

//        return true;
        $pubKey = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8EZC4e0J0Pjmpc42ArtswXdaH
X8wq/KXcMSbs7I7DQg+duOFrRP8+XrS6WZlGIUbYSMlQ0RU1HL+pKCdQ5woD0Tyw
XYr7a+IuutpvUt3bG5YKtWlZSdrpLcevhULSyokxn+V8fRyM1QJWDiHMe3QUakZv
jjlgQ0MobI9WRO05PwIDAQAB
-----END PUBLIC KEY-----";

        $publicKeyId = openssl_pkey_get_public($pubKey);

        $result = openssl_verify($toSign, base64_decode($sign), $publicKeyId);
        openssl_free_key($publicKeyId);

        return $result === 1 ? true : false;
    }


    public function actionIndex()
    {

        $param = Yii::$app->request->get();

        $checkResult = $this->checkSign($param['sign'], $param['signString']);

        $dingUser = [];
        if ($checkResult) {
            $signString = explode("&", base64_decode($param['signString']));
            foreach ($signString as $string) {
                $string = explode("=", $string);
                $dingUser[$string[0]] = $string[1];
            }


            $redirectUrl = "/";
            if (isset($param['redirect'])) $redirectUrl = $param['redirect'];

            $userInfo = array();

            $userInfo['userId'] = $dingUser['accountId'];
            $userInfo['userName'] = $dingUser['name'];

            $userShopIds = isset($dingUser['permissionShops']) ? explode(",", $dingUser['permissionShops']) : null;

            if (null != $userShopIds && count($userShopIds) > 0) {

                if (in_array(0, $userShopIds)) {
                    $shopId = '';
                } else {
                    $shopId = implode(",", $userShopIds);
                }

                $shopRes = api::post('comm/get-shop', array('shopId' => $shopId));

                $shopArray = array();
                $userInfo['shopType'] = 1;
                if ($shopRes['code'] == 200 && is_array($shopRes['data'])) {
                    foreach ($shopRes['data'] as $sd) {
                        $shopArray[] = array(
                            'shopId' => $sd['ShopID'],
                            'shopName' => $sd['ShopName'],
                            'add' => $sd['Address'],
                            'shopType' => $sd['shopType']
                        );
                        if ($sd['shopType'] == 0) { //如果有直营门店，则按照直营逻辑走
                            $userInfo['shopType'] = 0;
                        }
                    }
                }
                $userInfo['shopId'] = $shopId;
                $userInfo['shop'] = $shopArray;

                $this->setCache('USER', $userInfo, 0);
                $this->redirect($redirectUrl);
            } else {
                return "暂无权限！";
            }
        } else {
            return "暂无权限！";
        }

    }


    public function actionLogin()
    {

        return $this->render('login');
    }

    public function actionUserLogin()
    {

        $username = Yii::$app->request->post('username');
        $password = Yii::$app->request->post('password');

        $user_data = $this->CheckUser($username, $password);

        if (!$user_data) {
            $this->retJson('用户名密码不正确', 901);
            return;
        }

        if ($user_data['use_flg'] == 0) {
            $this->retJson('账号已锁定', 901);
            return;
        }

        $shopIds = $user_data['shop_ids'];
        if (!$shopIds || empty($shopIds)) {
            $this->retJson('无门店权限', 901);
        }


        $userInfo = array();

        $userInfo['userId'] = $user_data['id'];
        $userInfo['userName'] = $user_data['user_name'];

        $userShopIds = explode(",", $shopIds);

        if (in_array(0, $userShopIds)) {
            $shopId = '';
        } else {
            $shopId = implode(",", $userShopIds);
        }

        $shopRes = api::post('comm/get-shop', array('shopId' => $shopId));

        $shopArray = array();
        $userInfo['shopType'] = 1;
        if ($shopRes['code'] == 200 && is_array($shopRes['data'])) {
            foreach ($shopRes['data'] as $sd) {
                $shopArray[] = array(
                    'shopId' => $sd['ShopID'],
                    'shopName' => $sd['ShopName'],
                    'add' => $sd['Address'],
                    'shopType' => $sd['shopType']
                );
                if ($sd['shopType'] == 0) { //如果有直营门店，则按照直营逻辑走
                    $userInfo['shopType'] = 0;
                }
            }
        }
        $userInfo['shopId'] = $shopId;
        $userInfo['shop'] = $shopArray;

        $this->setCache('USER', $userInfo, 0);


        $this->retJson('登录成功', 200);
    }


    private function CheckUser($user, $pwd)
    {
        try {
            $post = Yii::$app->db->createCommand('SELECT * FROM j_user_master WHERE BINARY user_name = :user_name')
                ->bindValue(':user_name', $user)
                ->queryOne();
            if (!$post) {
                return false;
            }
            if ($post['user_pwd'] != tools::md5pwd($pwd)) {
                return false;
            }
            return $post;
        } catch (Exception $e) {
            return false;
        }
    }
}